from django.shortcuts import render,HttpResponse,redirect
from .models import Doctor,Prescription
from django.views import View
from django.core.paginator import Paginator
# Create your views here.
def index(request):
    return HttpResponse('ok')

def register(request):
    if request.method == 'GET':
        return render(request,'register.html')
    if request.method == 'POST':
        uname = request.POST.get('uname')
        truename = request.POST.get('truename')
        pwd = request.POST.get('pwd')
        Doctor.objects.create(uname=uname,truename=truename,pwd=pwd)
        return redirect('user:loginx')

class loginx(View):
    def get(self,request):
        return render(request,'loginx.html')
    def post(self,request):
        uname = request.POST.get('uname')
        pwd = request.POST.get('pwd')
        if Doctor.objects.filter(uname=uname,pwd=pwd):
            request.session['uname'] = uname
            return redirect('user:showp')
        else:
            return HttpResponse('账号或者密码错误')

def add_ption(request):
    if request.method == 'GET':
        listl = Doctor.objects.all()
        return render(request,'add_ption.html',{'listl':listl})
    if request.method == 'POST':
        cname = request.POST.get('cname')
        result = request.POST.get('result')
        hname = request.POST.get('hname')
        doctor = request.POST.get('doctor')
        Prescription.objects.create(cname=cname,result=result,hname=hname,doctor_id=doctor)
        return HttpResponse('处方添加成功')

def showp(request):
   cname = request.POST.get('cname')
   if cname:
       listl = Prescription.objects.filter(cname__contains=cname)
   else:
       listl = Prescription.objects.all()
   object_list = listl
   per_page = 3
   pagex = Paginator(object_list, per_page)
   page = request.GET.get('page', 1)
   page = int(page)
   res = pagex.get_page(page)
   listl = res.object_list
   max_page = pagex.num_pages
   if page > max_page:
       page = max_page
   elif page < 1:
       page = 1
   elif page == 0:
       page = 1
   return render(request, 'showp.html', {'listl': listl, 'page': page, 'cname': cname})

# 删除处方
def delp(request,id):
    Prescription.objects.get(id=id).delete()
    return redirect('user:showp')

# 修改
def update(request,id):
    listl = Doctor.objects.all()
    if request.method == 'POST':
        cname = request.POST.get('cname')
        result = request.POST.get('result')
        hname = request.POST.get('hname')
        doctor = request.POST.get('doctor')
        Prescription.objects.filter(id=id).update(
            cname=cname,
            result=result,
            hname = hname,
            doctor=doctor
        )
        return redirect('user:showp')
    date = Prescription.objects.filter(id=id)
    return render(request,'update.html',{'date':date,'listl':listl})